<template>
    <div class="dawn-job">
        <van-form @submit="handleSubmit">
            <van-cell-group inset>
                <!-- 任务函数 -->
                <van-field
                    v-model="form.function"
                    name="name"
                    label="任务函数"
                    placeholder="请选择任务函数"
                    :rules="[{ required: true, message: '请选择任务函数' }]"
                    readonly
                    @click="showFunctionPopup = true"
                >
                    <template #right-icon>
                        <van-icon name="arrow-down" />
                    </template>
                </van-field>


                <!-- 调度方式详细配置 -->
                    <van-field
                        v-model="form.cron"
                        name="cron"
                        label="Cron表达式"
                        placeholder="请输入或选择Cron表达式"
                        :rules="[
                            { required: true, message: '请输入Cron表达式' },
                            { validator: validateCron, message: 'Cron表达式格式错误' }
                        ]"
                        @input="updateNextExecutionTime"
                    >
                        <template #right-icon>
                            <div style="display: flex; align-items: center;">
                                <van-icon name="arrow-down" @click="showCronPopup = true" style="margin-right: 8px;" />
                                <van-icon name="question-o" @click="showCronHelp = true" />
                            </div>
                        </template>
                    </van-field>
                    
                    <!-- Cron执行时间提示 -->
                    <div v-if="form.cron && isValidCron" class="cron-next-time">
                        下次执行时间：{{ nextExecutionTime }}
                    </div>


                <van-field
                    v-model="form.time"
                    name="time_type"
                    label="执行时间设置"
                    placeholder="请选择任务函数"
                    :rules="[{ required: true, message: '' }]"
                    readonly
                    @click="showTimePopup = true"
                >
                    <template #right-icon>
                        <van-icon name="arrow-down" />
                    </template>
                </van-field>

                 <template v-if="form.time === 'jitter_time'">
                    <van-field
                    v-model="form.jitter_time"
                    name="jitter_time"
                    label="执行间隔(秒)"
                    placeholder="请输入执行间隔（格式如：2-3）， 单位是秒"
                    :rules="[
                        { required: true, message: '请输入执行间隔' },
                        { 
                            pattern: /^\d+-\d+$/, 
                            message: '请输入正确的格式（如：2-3）',
                            validator: (value) => {
                                const [min, max] = value.split('-').map(Number);
                                return min <= max;
                            }
                        }
                    ]"
                />

                 </template>
                 <template v-if="form.time === 'delay_time'">

                    <van-field
                        v-model="form.delay"
                        name="delay"
                        label="延迟时间(秒)"
                        type="number"
                        placeholder="请输入延迟时间"
                        :rules="[
                            { required: true, message: '请输入延迟时间' },
                        ]"
                    />

                </template>
                

            </van-cell-group>

            <div style="margin: 16px;">
                <van-button round block type="primary" native-type="submit" >
                    添加
                </van-button>
            </div>
        </van-form>

        <!-- 任务函数选择弹窗 -->
        <van-popup
            v-model:show="showFunctionPopup"
            position="bottom"
            round
            :style="{ height: '40%' }"
        >
            <van-picker
                :columns="functionTypes"
                @confirm="onFunctionConfirm"
                @cancel="showFunctionPopup = false"
                show-toolbar
                title="选择任务函数"
            />
        </van-popup>

        <!-- 时间函数选择弹窗 -->
        <van-popup
            v-model:show="showTimePopup"
            position="bottom"
            round
            :style="{ height: '40%' }"
        >
            <van-picker
                :columns="functionTime"
                @confirm="onTimeConfirm"
                @cancel="showTimePopup = false"
                show-toolbar
                title="选择任务函数"
            />
        </van-popup>


        <!-- Cron表达式选择弹窗 -->
        <van-popup
            v-model:show="showCronPopup"
            position="bottom"
            round
            :style="{ height: '40%' }"
        >
            <van-picker
                :columns="cronPresets"
                @confirm="onCronConfirm"
                @cancel="showCronPopup = false"
                show-toolbar
                title="选择Cron表达式"
            />
        </van-popup>

        <!-- Cron表达式帮助说明弹窗 -->
        <van-dialog
            v-model:show="showCronHelp"
            title="Cron表达式说明"
            :show-confirm-button="true"
            confirm-button-text="关闭"
            class="cron-help-dialog"
        >
            <div class="cron-help-content">
                <h3>Cron表达式格式：* * * * *</h3>
                <p>从左到右依次为：</p>
                <ul>
                    <li><strong>分钟</strong>：0-59</li>
                    <li><strong>小时</strong>：0-23</li>
                    <li><strong>日期</strong>：1-31</li>
                    <li><strong>月份</strong>：1-12</li>
                    <li><strong>星期</strong>：0-7（0和7都表示星期日）</li>
                </ul>
                <h4>特殊字符说明：</h4>
                <ul>
                    <li><strong>*</strong>：表示任意值</li>
                    <li><strong>,</strong>：表示多个值（如：1,3,5）</li>
                    <li><strong>-</strong>：表示范围（如：1-5）</li>
                    <li><strong>/</strong>：表示间隔（如：*/5）</li>
                </ul>
                <h4>常用示例：</h4>
                <ul>
                    <li><code>* * * * *</code>：每分钟执行</li>
                    <li><code>0 * * * *</code>：每小时整点执行</li>
                    <li><code>0 0 * * *</code>：每天凌晨执行</li>
                    <li><code>*/5 * * * *</code>：每5分钟执行一次</li>
                </ul>
            </div>
        </van-dialog>


    </div>
</template>

<script setup>
import { ref, computed, watch, defineEmits } from 'vue';
import { 
    Form as VanForm,
    Field as VanField,
    CellGroup as VanCellGroup,
    Button as VanButton,
    Popup as VanPopup,
    Picker as VanPicker,
    Icon as VanIcon,
    Dialog as VanDialog,
    showToast
} from 'vant';
import apiUrls from '@/config/apiUrls'; 
import request from '@/utils/request';
// 表单数据
const form = ref({
    function: '',
    schedule_type: '',
    cron: '',
    interval: '',
    delay: '',
    time:''
});
import { getNextExecutionTime } from '@/utils/utils';
// 弹窗控制
const showFunctionPopup = ref(false);
const showSchedulePopup = ref(false);
const showCronPopup = ref(false);
const showCronHelp = ref(false);
const showAddressPopup = ref(false);
const showAddressHelp = ref(false);
const showImageCountPopup = ref(false);
const showTimePopup = ref(false);

// 下次执行时间
const nextExecutionTime = ref('');

// Cron表达式验证
const isValidCron = ref(true);

const validateCron = (value) => {
    if (!value) return true;
    
    // 验证 Cron 表达式格式
    const cronRegex = /^(\*|([0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9])|(\*\/([0-9]|1[0-9]|2[0-9]|3[0-9]|4[0-9]|5[0-9]))) (\*|([0-9]|1[0-9]|2[0-3])|(\*\/([0-9]|1[0-9]|2[0-3]))) (\*|([1-9]|1[0-9]|2[0-9]|3[0-1])|(\*\/([1-9]|1[0-9]|2[0-9]|3[0-1]))) (\*|([1-9]|1[0-2])|(\*\/([1-9]|1[0-2]))) (\*|([0-7])|(\*\/[0-7]))$/;
    
    const isValid = cronRegex.test(value);
    isValidCron.value = isValid;
    return isValid;
};

// 监听 cron 表达式变化
watch(() => form.value.cron, (newValue) => {
    nextExecutionTime.value = getNextExecutionTime(newValue)
});

// 任务函数选项
const functionTypes = [
    { text: '定时打卡', value: 'dawn_job' },
    { text: '定时日志', value: 'log_job' },
];

// 时间函数选项
const functionTime = [
    { text: 'Cron时间执行', value: 'cron_expression' },
    { text: '固定时间执行', value: 'delay_time' },
    { text: '区间时间执行', value: 'jitter_time' },
];


// Cron表达式预设选项
const cronPresets = [
    { text: '每天早上8点执行', value: '0 8 * * *' },
    { text: '每天下午5点执行', value: '0 17 * * *' },
    { text: '每天晚上8点执行', value: '0 20 * * *' },
    { text: '每周六早上10点执行', value: '0 10 * * 6' },
    { text: '每周日早上10点执行', value: '0 10 * * 0' },
];


// 选择任务函数
const onFunctionConfirm = (value) => {
    form.value.function = value.selectedValues;
    showFunctionPopup.value = false;
};


// 选择时间函数
const onTimeConfirm = (value) => {
    form.value.time = value.selectedValues;
    showTimePopup.value = false;
};

// 选择Cron表达式
const onCronConfirm = (value) => {
    form.value.cron = value.selectedValues;
    showCronPopup.value = false;
};

const emit = defineEmits(['job-added']);

// 提交表单
const handleSubmit = async (values) => {
    try {
        console.log("提交数据");
        console.log(values);
        
        const response = await request.post(apiUrls.schedule.tasks, {
            data: values
        });
        if (response.code === 200){
            emit('job-added');
        }
        showToast(response.message);
    } catch (error) {
        showToast('保存失败');
        console.error('保存失败:', error);
    }
};

// 更新下次执行时间
const updateNextExecutionTime = () => {
    // 实现更新下次执行时间的逻辑
    
};
</script>

<style scoped>
.dawn-job {
    padding: 12px;
    background-color: #ffffff;
    max-width: 100%;
    box-sizing: border-box;
}

:deep(.van-form) {
    box-shadow: 0 2px 10px rgba(0, 137, 250, 0.06);
    border-radius: 12px;
    overflow: hidden;
    background-color: #fff;
    border: 1px solid rgba(25, 137, 250, 0.05);
}

:deep(.van-cell-group--inset) {
    margin: 0;
    border-radius: 8px;
    overflow: hidden;
}

:deep(.van-field) {
    padding: 14px 16px;
    background-color: #fff;
}

:deep(.van-field__label) {
    width: 100px;
    color: #323233;
    font-weight: 500;
}

:deep(.van-field__value) {
    width: calc(100% - 100px);
}

:deep(.van-field__control) {
    font-size: 14px;
}

:deep(.van-button) {
    height: 44px;
    border-radius: 8px;
    font-weight: 500;
    font-size: 16px;
    box-shadow: 0 2px 8px rgba(25, 137, 250, 0.15);
    transition: all 0.3s ease;
    background-color: #1989fa;
    border-color: #1989fa;
}

:deep(.van-button:active) {
    transform: scale(0.98);
    box-shadow: 0 1px 4px rgba(25, 137, 250, 0.1);
}

:deep(.van-icon) {
    font-size: 18px;
    padding: 4px;
    touch-action: manipulation;
}

.cron-help-content {
    padding: 16px;
    font-size: 14px;
    line-height: 1.6;
}

.cron-help-content h3 {
    margin-bottom: 12px;
    color: #323233;
    font-weight: 600;
}

.cron-help-content h4 {
    margin: 16px 0 8px;
    color: #323233;
    font-weight: 600;
}

.cron-help-content p {
    margin: 8px 0;
    color: #666;
}

.cron-help-content ul {
    margin: 8px 0;
    padding-left: 20px;
    color: #666;
}

.cron-help-content li {
    margin: 4px 0;
}

.cron-help-content code {
    background-color: #f5f5f5;
    padding: 2px 6px;
    border-radius: 4px;
    font-family: monospace;
}

.cron-next-time {
    padding: 8px 16px;
    color: #666;
    font-size: 14px;
    background-color: #f7f9fe;
    margin: 4px 16px;
    border-radius: 4px;
    border: 1px solid rgba(25, 137, 250, 0.05);
}

.cron-error {
    color: #ee0a24;
    background-color: #fff5f5;
}

:deep(.van-dialog) {
    max-height: 80vh;
    overflow-y: auto;
    border-radius: 12px;
}

:deep(.van-popup) {
    border-radius: 16px 16px 0 0;
}

.help-content {
    padding: 16px;
    font-size: 14px;
    line-height: 1.6;
}

.help-content h3 {
    margin-bottom: 12px;
    color: #323233;
    font-weight: 600;
}

.help-content h4 {
    margin: 16px 0 8px;
    color: #323233;
    font-weight: 600;
}

.help-content p {
    margin: 8px 0;
    color: #666;
}

.help-content ul {
    margin: 8px 0;
    padding-left: 20px;
    color: #666;
}

.help-content li {
    margin: 4px 0;
}

.help-content code {
    background-color: #f5f5f5;
    padding: 2px 6px;
    border-radius: 4px;
    font-family: monospace;
}

/* 移动端适配 */
@media screen and (max-width: 480px) {
    .dawn-job {
        padding: 8px;
    }

    :deep(.van-field) {
        padding: 10px;
    }

    :deep(.van-field__label) {
        width: 80px;
        font-size: 13px;
    }

    :deep(.van-field__value) {
        width: calc(100% - 80px);
    }
    
    .cron-next-time {
        padding: 6px 12px;
        font-size: 13px;
        margin: 4px 12px;
    }
    
    :deep(.van-dialog) {
        width: 90%;
        max-width: 360px;
    }
    
    .cron-help-content h3,
    .help-content h3 {
        font-size: 15px;
    }
    
    .cron-help-content h4,
    .help-content h4 {
        font-size: 14px;
    }
}
</style>